import {_decorator, Component, director, Label, Node, ProgressBar} from 'cc';
import {HeadComp} from '../mainui/head-comp';
import {GameEvent} from '../../game-event';
import {lobby} from '../../lobby';
import {FishInfoComp} from './fish-info-comp';
import {userInfo} from "db://assets/script/user-info";
import {FreshImmortal} from '../../../proto/shared/v1/wuni';
import {configsHelper} from "db://assets/script/configs-helper";
import Long from "long";
import {fishUtils} from "db://assets/script/utils/fish-utils";
import maxNormalHealth = fishUtils.maxNormalHealth;
import {max} from "lodash";

const {ccclass, property} = _decorator;

@ccclass('FishComp')
export class FishComp extends Component {


    @property(ProgressBar)
    progressbar!: ProgressBar;

    @property(Label)
    statusLabel!: Label;

    @property(HeadComp)
    head!: HeadComp;

    fishId!: Long

    start() {
        director.on(GameEvent.userFishRemove, this.removeFish, this)
        director.on(GameEvent.uiUpdateFish, this._updateUI, this)
        this.node.on(Node.EventType.TOUCH_END, () => {
            const fishInfoUI = lobby.instance.addUI("prefab/fish-info")
            fishInfoUI.getComponent(FishInfoComp)!.changeFish(this.fishId)
        })
    }

    setFish(fishId: Long) {
        this.fishId = fishId;
        const ff = userInfo.fishInfo.loadFishById(fishId)
        if (ff) this.head.setHead(fishId, ff.baseInfo!.gender, ff.baseInfo!.talent, ff.masterInfo!.masterId.toString())
        this._updateUI(fishId)
    }

    removeFish(fish: FreshImmortal) {
        if (this.fishId == fish!.id) {
            this.node.destroy()
        }
    }

    _updateUI(fishId: Long) {
        if (fishId.neq(this.fishId)) return
        const ff = userInfo.fishInfo.loadFishById(this.fishId)
        if (ff) {
            const currentHeal = Math.max(ff!.battleInfo!.currentNormalHealth.toNumber(), 0)
            const maxHeal = maxNormalHealth(ff!.battleInfo!.finalBattleInfo!)
            this.progressbar.progress = currentHeal / maxHeal;
            this.statusLabel.string = configsHelper.loadStatusStr(ff.status!)
        }
    }

    protected onDestroy(): void {
        director.off(GameEvent.userFishRemove, this.removeFish, this)
    }

    update(deltaTime: number) {
    }
}